{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Subdomain Visit Count"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #array #hash-table #string #counting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #数组 #哈希表 #字符串 #计数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: subdomainVisits"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #子域名访问计数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>网站域名 <code>\"discuss.leetcode.com\"</code> 由多个子域名组成。顶级域名为 <code>\"com\"</code> ，二级域名为 <code>\"leetcode.com\"</code> ，最低一级为 <code>\"discuss.leetcode.com\"</code> 。当访问域名 <code>\"discuss.leetcode.com\"</code> 时，同时也会隐式访问其父域名 <code>\"leetcode.com\" </code>以及 <code>\"com\"</code> 。</p>\n",
    "\n",
    "<p><strong>计数配对域名</strong> 是遵循 <code>\"rep d1.d2.d3\"</code> 或 <code>\"rep d1.d2\"</code> 格式的一个域名表示，其中 <code>rep</code> 表示访问域名的次数，<code>d1.d2.d3</code> 为域名本身。</p>\n",
    "\n",
    "<ul>\n",
    "\t<li>例如，<code>\"9001 discuss.leetcode.com\"</code> 就是一个 <strong>计数配对域名</strong> ，表示 <code>discuss.leetcode.com</code> 被访问了 <code>9001</code> 次。</li>\n",
    "</ul>\n",
    "\n",
    "<p>给你一个<strong> 计数配对域名 </strong>组成的数组 <code>cpdomains</code> ，解析得到输入中每个子域名对应的&nbsp;<strong>计数配对域名</strong> ，并以数组形式返回。可以按 <strong>任意顺序</strong> 返回答案。</p>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>示例 1：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>cpdomains = [\"9001 discuss.leetcode.com\"]\n",
    "<strong>输出：</strong>[\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]\n",
    "<strong>解释：</strong>例子中仅包含一个网站域名：\"discuss.leetcode.com\"。\n",
    "按照前文描述，子域名 \"leetcode.com\" 和 \"com\" 都会被访问，所以它们都被访问了 9001 次。</pre>\n",
    "\n",
    "<p><strong>示例 2：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\n",
    "<strong>输出：</strong>[\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]\n",
    "<strong>解释：</strong>按照前文描述，会访问 \"google.mail.com\" 900 次，\"yahoo.com\" 50 次，\"intel.mail.com\" 1 次，\"wiki.org\" 5 次。\n",
    "而对于父域名，会访问 \"mail.com\" 900 + 1 = 901 次，\"com\" 900 + 50 + 1 = 951 次，和 \"org\" 5 次。\n",
    "</pre>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>1 &lt;= cpdomain.length &lt;= 100</code></li>\n",
    "\t<li><code>1 &lt;= cpdomain[i].length &lt;= 100</code></li>\n",
    "\t<li><code>cpdomain[i]</code> 会遵循 <code>\"rep<sub>i</sub> d1<sub>i</sub>.d2<sub>i</sub>.d3<sub>i</sub>\"</code> 或 <code>\"rep<sub>i</sub> d1<sub>i</sub>.d2<sub>i</sub>\"</code> 格式</li>\n",
    "\t<li><code>rep<sub>i</sub></code> 是范围 <code>[1, 10<sup>4</sup>]</code> 内的一个整数</li>\n",
    "\t<li><code>d1<sub>i</sub></code>、<code>d2<sub>i</sub></code> 和 <code>d3<sub>i</sub></code> 由小写英文字母组成</li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [subdomain-visit-count](https://leetcode.cn/problems/subdomain-visit-count/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [subdomain-visit-count](https://leetcode.cn/problems/subdomain-visit-count/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['[\"9001 discuss.leetcode.com\"]', '[\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        pairs={}\n",
    "        for p in cpdomains:\n",
    "            c,d=p.split(' ')\n",
    "            count=eval(c)\n",
    "            domain=d.split('.')\n",
    "            for i in range(len(domain)):\n",
    "                s='.'.join(domain[i:])\n",
    "                if s in pairs:\n",
    "                    pairs[s]+=count\n",
    "                else:\n",
    "                    pairs[s]=count\n",
    "        out=[]\n",
    "        for key,value in pairs.items():\n",
    "            out.append(str(value)+' '+key)\n",
    "        return out\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import defaultdict\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        countMap = defaultdict(int)\n",
    "        for cpdomain in cpdomains:\n",
    "            cpdomain = cpdomain.strip('\"')\n",
    "            \n",
    "            cp = cpdomain.split(' ')\n",
    "            domains = cp[1] \n",
    "            \n",
    "            countMap[domains] += int(cp[0])\n",
    "            i = domains.find('.')\n",
    "            while 0 < i < len(domains)  :\n",
    "                countMap[domains[i + 1:]] += int(cp[0])\n",
    "                domains = domains[i + 1:]\n",
    "                i = domains.find('.')\n",
    "        rs = []\n",
    "        for d in countMap.keys():\n",
    "            rs.append(str(countMap[d]) + ' ' + d)\n",
    "        return rs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import defaultdict\r\n",
    "\r\n",
    "class Solution:\r\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\r\n",
    "        ret = defaultdict(int)\r\n",
    "\r\n",
    "        for cpdomain in cpdomains:\r\n",
    "            count, domain = cpdomain.split()\r\n",
    "            count = int(count)\r\n",
    "\r\n",
    "            ret[domain] += count\r\n",
    "\r\n",
    "            domain_arr = domain.split('.')\r\n",
    "\r\n",
    "            for i in range(1, len(domain_arr)):\r\n",
    "                ret['.'.join(domain_arr[i:])] += count\r\n",
    "\r\n",
    "        return [str(count) + ' ' + domain for domain, count in ret.items()]\r\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        # from collections import Counter\n",
    "        # cnt=Counter()\n",
    "        # for dom in cpdomains:\n",
    "        #     c,s=dom.split()\n",
    "        #     c=int(c)\n",
    "        #     cnt[s]+=c\n",
    "        #     while '.' in s:\n",
    "        #         s=s[s.index('.')+1:]\n",
    "        #         cnt[s]+=c\n",
    "        # return ['{} {}'.format(c,s) for s,c in cnt.items()]  \n",
    "        cnt = Counter()\n",
    "        for domain in cpdomains:\n",
    "            c, s = domain.split()\n",
    "            c = int(c)\n",
    "            cnt[s] += c\n",
    "            while '.' in s:\n",
    "                s = s[s.index('.') + 1:]\n",
    "                cnt[s] += c\n",
    "        # return [f'{c} {s}' for s, c in cnt.items()]\n",
    "        return [\"{} {}\".format(c, s) for s, c in cnt.items()]              "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        from collections import defaultdict\n",
    "        d = defaultdict(int)\n",
    "        for s in cpdomains:\n",
    "            v = int(s.split()[0])\n",
    "            l = s.split()[1].split('.')\n",
    "            re = l[-1]\n",
    "            d[re] += v\n",
    "            for i in range(len(l)-2, -1, -1):\n",
    "                re = l[i]+'.'+re\n",
    "                d[re] += v\n",
    "        res = []\n",
    "        for key,value in d.items():\n",
    "            res.append(str(value)+' '+key)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        result_dict = collections.defaultdict(int)\n",
    "        result = []\n",
    "        for cpdomain in cpdomains:\n",
    "            visit_count = int(cpdomain.split(' ')[0])\n",
    "            split_url = cpdomain.split(' ')[1].split('.')\n",
    "            domain = split_url[-1]\n",
    "            result_dict[domain] += visit_count\n",
    "            for i in range(len(split_url) - 2, -1, -1):\n",
    "                domain = '{}.{}'.format(split_url[i], domain)\n",
    "                result_dict[domain] += visit_count\n",
    "        for key, value in result_dict.items():\n",
    "            result.append('{} {}'.format(value, key))\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        dic = {}\n",
    "        for i in range(len(cpdomains)):\n",
    "            lst = list(cpdomains[i].split())\n",
    "            cishu = int(lst[0])\n",
    "            \n",
    "            s = lst.pop()\n",
    "            dian_cnt = s.count('.')\n",
    "            if s not in dic:\n",
    "                dic[s] = cishu\n",
    "            else:\n",
    "                dic[s] += cishu\n",
    "            for i in range(len(s)):\n",
    "                if s[i] == '.':\n",
    "                    if s[i+1:] not in dic:\n",
    "                        dic[s[i+1:]] = cishu\n",
    "                    else:\n",
    "                        dic[s[i+1:]] += cishu\n",
    "            \n",
    "        res = []\n",
    "        for items,values in dic.items():\n",
    "            #print(items)\n",
    "            stmp = str(values) + ' ' +items\n",
    "            res.append(stmp)\n",
    "        return res\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        counter={}\n",
    "        for cpdomain in cpdomains:\n",
    "            times,domain=cpdomain.split()\n",
    "            times=int(times)\n",
    "            dots=domain.count('.')\n",
    "            for i in range(dots+1):\n",
    "                d=domain.split('.',i)[-1]\n",
    "                counter[d]=counter.get(d,0)+times\n",
    "        ans=[]\n",
    "        for domain,times in counter.items():\n",
    "           ans.append(f'{times} {domain}')\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt = Counter()\n",
    "        for s in cpdomains:\n",
    "            v = int(s[:s.index(' ')])\n",
    "            for i, c in enumerate(s):\n",
    "                if c in ' .':\n",
    "                    cnt[s[i + 1:]] += v\n",
    "        return [f'{v} {s}' for s, v in cnt.items()]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        domainCnt = collections.defaultdict(int)\n",
    "        for cpd in cpdomains:\n",
    "            cnt, name = cpd.split()\n",
    "            cnt = int(cnt)\n",
    "            name = name.split('.')\n",
    "            n = len(name)\n",
    "            for i in range(n - 1, -1, -1):\n",
    "                domain = '.'.join(name[i:])\n",
    "                domainCnt[domain] += cnt\n",
    "        ans = []\n",
    "        for domain in domainCnt:\n",
    "            ansStr = str(domainCnt[domain]) + \" \" + domain\n",
    "            ans.append(ansStr)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt = collections.Counter()\n",
    "        for domain in cpdomains:\n",
    "            c, s = domain.split()\n",
    "            c = int(c)\n",
    "            cnt[s] += c\n",
    "            while '.' in s:\n",
    "                s = s[s.index('.') + 1:]\n",
    "                cnt[s] += c\n",
    "        return [f\"{c} {s}\" for s, c in cnt.items()]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        maps={}\n",
    "        for sen in cpdomains:\n",
    "            sen=sen.split(' ')\n",
    "            num=int(sen[0])\n",
    "            name=sen[1]\n",
    "\n",
    "            tmp=''\n",
    "            for i in range(len(name)-1,-1,-1):\n",
    "                if name[i]!='.':\n",
    "                    tmp=name[i]+tmp\n",
    "                else:\n",
    "                    if tmp in maps:\n",
    "                        maps[tmp]+=num\n",
    "                    else:\n",
    "                        maps[tmp]=num\n",
    "                    tmp=name[i]+tmp\n",
    "            if tmp in maps:\n",
    "                maps[tmp]+=num\n",
    "            else:\n",
    "                maps[tmp]=num\n",
    "        result=[]\n",
    "        for k in maps.keys():\n",
    "            result.append(str(maps[k])+' '+k )\n",
    "        return result\n",
    "\n",
    "        \n",
    "            \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        record = dict()\n",
    "        for cpdomain in cpdomains:\n",
    "            rep = int(cpdomain.split(' ')[0])\n",
    "            domain = cpdomain.split(' ')[1]\n",
    "            subs = domain.split('.')\n",
    "            for i in range(len(subs)):\n",
    "                key = '.'.join(subs[i:])\n",
    "                if key in record.keys():\n",
    "                    record[key] += rep\n",
    "                else:\n",
    "                    record[key] = rep\n",
    "        res = [f\"{val} {key}\" for key, val in record.items()]\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def get_dict(self, cpdomain:str):\n",
    "        text=cpdomain.split(\" \")\n",
    "        num=text[0]\n",
    "        add=text[1]\n",
    "        subadd=add.split(\".\")\n",
    "        domain=[]\n",
    "        d_dict={}\n",
    "        for i in range(len(subadd)):\n",
    "            domain.append(subadd[-(i+1)])\n",
    "            redomain=[]\n",
    "            for i in range(len(domain)):\n",
    "                redomain.append(domain[-(i+1)])\n",
    "            key=\".\".join(redomain)\n",
    "            d_dict.update({key:num})\n",
    "        return d_dict\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        domain_str=[]\n",
    "        domain_dict={}\n",
    "        for cpdomain in cpdomains:\n",
    "            d_dict=self.get_dict( cpdomain)\n",
    "            for d_key,d_value in d_dict.items():\n",
    "                if d_key in list(domain_dict.keys()):\n",
    "                    domain_dict[d_key]=int(domain_dict[d_key])+int(d_dict[d_key])\n",
    "                else:\n",
    "                    domain_dict.update({d_key:d_dict[d_key]})\n",
    "        for key,value in domain_dict.items():\n",
    "            domain_str.append(str(value)+\" \"+key)\n",
    "        return domain_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt = Counter()\n",
    "        for domain in cpdomains:\n",
    "            c, s = domain.split()\n",
    "            c = int(c)\n",
    "            cnt[s] += c\n",
    "            while '.' in s:\n",
    "                s = s[s.index('.') + 1 : ]\n",
    "                cnt[s] += c\n",
    "            \n",
    "        return [f\"{c} {s}\" for s, c in cnt.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt = Counter()\n",
    "        for domain in cpdomains:\n",
    "            c, s = domain.split()\n",
    "            c = int(c)\n",
    "            cnt[s] += c\n",
    "            while '.' in s:\n",
    "                s = s[s.index('.') + 1:]\n",
    "                cnt[s] += c\n",
    "        return [f\"{c} {s}\" for s, c in cnt.items()]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cp = {}\n",
    "        for i in cpdomains:\n",
    "            l = i.split(' ')\n",
    "            n = int(l[0])\n",
    "            q = l[1].split('.')\n",
    "            for c in range(len(q)):\n",
    "                tem = '.'.join(q[c:])\n",
    "                if tem not in cp.keys():\n",
    "                    cp[tem] = n\n",
    "                else:\n",
    "                    cp[tem] += n\n",
    "        ans = []\n",
    "        for i in cp:\n",
    "            ans.append(str(cp[i]) + ' ' + i)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        result_dict = collections.defaultdict(int)\n",
    "        result = []\n",
    "        for cpdomain in cpdomains:\n",
    "            tmp = cpdomain.split(' ')\n",
    "            visit_count = int(tmp[0])\n",
    "            split_url = tmp[1].split('.')\n",
    "            domain = split_url[-1]\n",
    "            result_dict[domain] += visit_count\n",
    "            for i in range(len(split_url) - 2, -1, -1):\n",
    "                domain = '{}.{}'.format(split_url[i], domain)\n",
    "                result_dict[domain] += visit_count\n",
    "        for key, value in result_dict.items():\n",
    "            result.append('{} {}'.format(value, key))\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        di = {}\n",
    "        for cpdomain in cpdomains:\n",
    "            cnt, domain = cpdomain.split(' ')\n",
    "            cnt = int(cnt)\n",
    "            domain_li = []\n",
    "            domain = domain.split('.')\n",
    "            for i in range(len(domain)):\n",
    "                do = '.'.join(domain[i:])\n",
    "                di[do] = di.get(do, 0) + cnt\n",
    "        return [str(v) + ' ' + k for k, v in di.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt = Counter()\n",
    "        for domain in cpdomains:\n",
    "            c, s = domain.split(' ')\n",
    "            c = int(c)\n",
    "            cnt[s] += c\n",
    "            while '.' in s:\n",
    "                s = s[s.index('.') + 1:]\n",
    "                cnt[s] += c\n",
    "        return [f\"{c} {s}\" for s, c in cnt.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        d = defaultdict(int)\n",
    "        for cpdomain in cpdomains:\n",
    "            cnt, domain = cpdomain.split()\n",
    "            cnt = int(cnt)\n",
    "            x = domain.split('.')\n",
    "            for i in range(len(x)):\n",
    "                y = '.'.join(x[i:])\n",
    "                d[y] += cnt\n",
    "        return [str(v) + ' ' + k for k, v in d.items()]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from typing import List\n",
    "class MyTree:\n",
    "    def __init__(self) -> None:\n",
    "        self.data = ['ROOT', 0, []]\n",
    "    \n",
    "    def update(self, path: list[str], freq: int):\n",
    "        path.append('ROOT')\n",
    "        length = len(path) - 1\n",
    "\n",
    "        def dfs(node: list, length: int):\n",
    "            \n",
    "            node[1] += freq\n",
    "            nexts = node[2]\n",
    "            length -= 1\n",
    "            \n",
    "            if length < 0:\n",
    "                return\n",
    "\n",
    "            have_flg = False\n",
    "            for index in range(len(nexts)):\n",
    "                if nexts[index][0] == path[length]:\n",
    "                    dfs(nexts[index], length)\n",
    "                    have_flg = True\n",
    "\n",
    "            if not have_flg:\n",
    "                nexts.append([path[length], 0, []])\n",
    "                dfs(nexts[-1], length)\n",
    "        \n",
    "        dfs(self.data, length)\n",
    "\n",
    "    def print(self):\n",
    "\n",
    "        result = []\n",
    "\n",
    "        def dfs(node: list, domain: list) -> None:\n",
    "            domain.append(node[0])\n",
    "            result.append(str(node[1]) + ' ' + '.'.join(domain[::-1]))\n",
    "\n",
    "            if not node[2]:\n",
    "                return\n",
    "            else:\n",
    "                for sub_node in node[2]:\n",
    "                    dfs(sub_node, domain.copy())\n",
    "        \n",
    "        for sub in self.data[2]:\n",
    "            dfs(sub, [])\n",
    "\n",
    "        return result\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        \n",
    "        tree = MyTree()\n",
    "\n",
    "        for cp_domain in cpdomains:\n",
    "            freq, domain = cp_domain.split()\n",
    "            freq = int(freq)\n",
    "            domains = domain.split('.')\n",
    "\n",
    "            tree.update(domains, freq)\n",
    "        \n",
    "        return tree.print()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        map = {}\n",
    "        for s in cpdomains:\n",
    "            n = len(s)\n",
    "            idx = 0\n",
    "            while idx<n and s[idx] != ' ':\n",
    "                idx +=1\n",
    "\n",
    "            cnt = int(s[:idx])\n",
    "\n",
    "            start = idx+1\n",
    "            idx = n-1\n",
    "\n",
    "            while idx>=start:\n",
    "                while idx>=start and s[idx] != '.':\n",
    "                    idx -=1\n",
    "\n",
    "                cur = s[idx+1:]\n",
    "                map[cur] = map.get(cur,0)+cnt\n",
    "                idx -=1\n",
    "\n",
    "        ans = []\n",
    "        for key in map:\n",
    "            ans.append(str(map[key])+' '+key)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt=Counter()\n",
    "        for dom in cpdomains:\n",
    "            c,s=dom.split()\n",
    "            c=int(c)\n",
    "            cnt[s]+=c\n",
    "            while '.' in s:\n",
    "                s=s[s.index('.')+1:]\n",
    "                cnt[s]+=c\n",
    "        return ['{} {}'.format(c,s) for s,c in cnt.items()]        \n",
    "\n",
    "      \n",
    " \n",
    "        # cnt = Counter()\n",
    "        # for domain in cpdomains:\n",
    "        #     c, s = domain.split()\n",
    "        #     c = int(c)\n",
    "        #     cnt[s] += c\n",
    "        #     while '.' in s:\n",
    "        #         s = s[s.index('.') + 1:]\n",
    "        #         cnt[s] += c\n",
    "        # # return [f'{c} {s}' for s, c in cnt.items()]\n",
    "        # return [\"{} {}\".format(c, s) for s, c in cnt.items()]              "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt = Counter()\n",
    "        for x in cpdomains:\n",
    "            s = x.split()\n",
    "            t = int(s[0])\n",
    "            s = ''.join(s[1:]).split('.')\n",
    "            for i in range(len(s)):\n",
    "                cnt['.'.join(s[i:])] += t\n",
    "        return [str(v) + ' ' + k for k,v in cnt.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\r\n",
    "        record = dict()\r\n",
    "        for cpdomain in cpdomains:\r\n",
    "            num, net = cpdomain.split(' ')\r\n",
    "            num = int(num)\r\n",
    "            net = net.split('.')\r\n",
    "            n = len(net)\r\n",
    "            for i in range(n):\r\n",
    "                yuming = '.'.join(net[i:])\r\n",
    "                record.setdefault(yuming, 0)\r\n",
    "                record[yuming] += num\r\n",
    "        ans = list()\r\n",
    "        for key in record:\r\n",
    "            ans.append(str(record[key]) + ' ' + key)\r\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from typing import List\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        ans = []\n",
    "        tongji_dcit = dict()\n",
    "        for index, cpd in enumerate(cpdomains):\n",
    "            cpd_list = cpd.split()\n",
    "            num = int(cpd_list[0])\n",
    "            yuming_list = cpd_list[1].split('.')[::-1]\n",
    "            #print(yuming_list)\n",
    "            str_data = ''\n",
    "            for yuming in yuming_list:\n",
    "                str_data = yuming + '.' + str_data\n",
    "                str_data = str_data.strip('.')\n",
    "                tongji_dcit[str_data] = tongji_dcit.get(str_data, 0) + num\n",
    "\n",
    "        #print(tongji_dcit)\n",
    "        for key, value in tongji_dcit.items():\n",
    "            ans.append(str(value) + ' ' + key)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt_dict = dict()\n",
    "        for cpdomain in cpdomains:\n",
    "            cpdomain = cpdomain.split(' ')\n",
    "            cnt = int(cpdomain[0])\n",
    "            domain = cpdomain[1]\n",
    "            domain = domain.split('.')\n",
    "            tmp = ''\n",
    "            for d in domain[::-1]:\n",
    "                if not tmp:\n",
    "                    tmp = d\n",
    "                else:\n",
    "                    tmp = d + '.' + tmp\n",
    "                cnt_dict[tmp] = cnt_dict.get(tmp, 0) + cnt\n",
    "\n",
    "        ans = []\n",
    "        for domain, cnt in cnt_dict.items():\n",
    "            sub = [str(cnt), domain]\n",
    "            ans.append(' '.join(sub))\n",
    "        \n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        # 使用哈希表记录每个子域名的计数\n",
    "        hashmp = collections.defaultdict(int)\n",
    "\n",
    "        # 遍历数组\n",
    "        for ch in cpdomains:\n",
    "\n",
    "            # 获取当前字符串的长度\n",
    "            n = len(ch)\n",
    "\n",
    "            # 每个字符串都是由数字 + 域名组成\n",
    "            # 先去获取这个字符串中的数字\n",
    "            # 从 0 开始，向后扫描到空格位置\n",
    "            idx = 0\n",
    "\n",
    "            # 从前向后扫描到空格位置\n",
    "            while idx < n and ch[idx] != ' ':\n",
    "                idx += 1\n",
    "\n",
    "            # 截取出数字来\n",
    "            num = int(ch[:idx])\n",
    "\n",
    "            # 从后往前处理域名部分，直到处理完毕\n",
    "            start = idx + 1 # 开始位置从域名的第一个字符开始\n",
    "            idx = n - 1\n",
    "            \n",
    "\n",
    "            # 直到处理完毕\n",
    "            while idx >= start:\n",
    "\n",
    "                # 每个域名由多个子域名组成\n",
    "                # 通过 . 来截取\n",
    "                while idx >= start and ch[idx] != '.':\n",
    "                    idx -= 1\n",
    "\n",
    "                # 获取当前子域名\n",
    "                cur = ch[idx + 1:]\n",
    "\n",
    "                # 更新这个子域名的计数\n",
    "                hashmp[cur] += num\n",
    "\n",
    "                # idx 继续向前移动\n",
    "                idx -= 1\n",
    "\n",
    "        # 从哈希表中构造出数组答案来\n",
    "        ans = []\n",
    "\n",
    "        for key in hashmp:\n",
    "            # key 是域名，map[key] 获取 value\n",
    "            ans.append(str(hashmp[key]) + ' ' + key)\n",
    "\n",
    "        # 返回结果\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        if not cpdomains:\n",
    "            return []\n",
    "        times_dict = dict()\n",
    "        for cpdomain in cpdomains:\n",
    "            times, domain = cpdomain.split()\n",
    "            times = int(times)\n",
    "\n",
    "            domain_list = domain.split('.')\n",
    "            for i in range(len(domain_list) - 1, -1, -1):\n",
    "                sub_domain = '.'.join(domain_list[i:])\n",
    "                if sub_domain not in times_dict:\n",
    "                    times_dict[sub_domain] = times\n",
    "                else:\n",
    "                    times_dict[sub_domain] += times\n",
    "\n",
    "        # res = []\n",
    "        # for key in times_dict.keys():\n",
    "        #     res.append(str(times_dict[key]) + ' ' + key)\n",
    "        # return res \n",
    "\n",
    "        return [str(count) + ' ' + key for key, count in times_dict.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "\n",
    "        dic = defaultdict(int)\n",
    "\n",
    "        for word in cpdomains:\n",
    "            count, domain = word.split(\" \")\n",
    "\n",
    "            dic[domain] += int(count)\n",
    "\n",
    "            while '.' in domain:\n",
    "                ind = domain.index('.')\n",
    "\n",
    "                domain = domain[ind + 1 : ]\n",
    "                dic[domain] += int(count)\n",
    "        \n",
    "        res = []\n",
    "        for key in dic:\n",
    "            res.append(str(dic[key]) + \" \" + key)\n",
    "        return res\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        dic = dict()\n",
    "        for domains in cpdomains:\n",
    "            num, tmp = domains.split(' ')\n",
    "            tmp = tmp.split('.')\n",
    "            for i in range(len(tmp)):\n",
    "                key = '.'.join(tmp[i:])\n",
    "                dic[key] = dic.get(key, 0) + int(num)\n",
    "        res = []\n",
    "        for k, v in dic.items():\n",
    "            res.append(str(v) + ' ' + k)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        dic=defaultdict(int)\n",
    "        for domain in cpdomains:\n",
    "            num,internet=domain.split()\n",
    "            num=int(num)\n",
    "            dic[internet]+=num\n",
    "            while '.' in internet:\n",
    "                internet=internet[internet.index('.')+1:]\n",
    "                dic[internet]+=num\n",
    "        return [f\"{num} {st}\"for st,num in dic.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        d = dict()\n",
    "        for ip in cpdomains:\n",
    "            a, b = ip.split()\n",
    "            s1 = \"\"\n",
    "            temp = b.split('.')\n",
    "            for i in range(len(temp) - 1, -1, -1):\n",
    "                s1 = temp[i] + \".\" + s1\n",
    "                if s1 in d:\n",
    "                    d[s1] += int(a)\n",
    "                else:\n",
    "                    d.update({s1: int(a)})\n",
    "        result = []\n",
    "        for k in d:\n",
    "            s = str(d[k]) + \" \" + k[: -1]\n",
    "            result.append(s)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        ans = collections.defaultdict(int)\n",
    "        for cpdomain in cpdomains:\n",
    "            cnt, name = cpdomain.split(' ')\n",
    "            cnt = int(cnt)\n",
    "            parts = name.split('.')\n",
    "            tmp = collections.deque()\n",
    "            for i in range(len(parts) - 1, -1, -1):\n",
    "                tmp.appendleft(parts[i])\n",
    "                val = '.'.join(tmp)\n",
    "                ans[val] += cnt\n",
    "        return [str(ans[k]) + ' ' + k for k in ans]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        from collections import Counter\n",
    "        cnt=Counter()\n",
    "        for dom in cpdomains:\n",
    "            c,s=dom.split()\n",
    "            c=int(c)\n",
    "            cnt[s]+=c\n",
    "            while '.' in s:\n",
    "                s=s[s.index('.')+1:]\n",
    "                cnt[s]+=c\n",
    "        return ['{} {}'.format(c,s) for s,c in cnt.items()]  \n",
    "        # cnt = Counter()\n",
    "        # for domain in cpdomains:\n",
    "        #     c, s = domain.split()\n",
    "        #     c = int(c)\n",
    "        #     cnt[s] += c\n",
    "        #     while '.' in s:\n",
    "        #         s = s[s.index('.') + 1:]\n",
    "        #         cnt[s] += c\n",
    "        # # return [f'{c} {s}' for s, c in cnt.items()]\n",
    "        # return [\"{} {}\".format(c, s) for s, c in cnt.items()]              "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        res = defaultdict(int)\n",
    "        for cpdomain in cpdomains:\n",
    "            cnt, domain = cpdomain.split()\n",
    "            res[domain] += int(cnt)\n",
    "            subarr = domain.split(\".\")\n",
    "            res[subarr[-1]] += int(cnt)\n",
    "            if len(subarr) == 3:\n",
    "                res['.'.join(subarr[-2:])] += int(cnt)\n",
    "\n",
    "        return [f\"{value} {key}\"for key, value in res.items()]\n",
    "            \n",
    "\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        dt = collections.defaultdict(int)\n",
    "\n",
    "        for c in cpdomains:\n",
    "            i = 0\n",
    "            cnt = 0\n",
    "            while i < len(c) and c[i].isdigit():\n",
    "                cnt *= 10 \n",
    "                cnt += int(c[i])\n",
    "                i += 1\n",
    "\n",
    "            ## cnt == 900\n",
    "            i += 1\n",
    "            j = len(c) - 1\n",
    "            s = \"\"\n",
    "            while j >= i :\n",
    "                if c[j].islower():\n",
    "                    s = c[j] + s\n",
    "                elif c[j] ==  '.':\n",
    "                    dt[s] += cnt\n",
    "                    s = c[j] + s\n",
    "                j-=1\n",
    "            dt[s] += cnt\n",
    "        # print(dt)\n",
    "        res = []\n",
    "        for k in dt.keys():\n",
    "            tmp = str(dt[k]) + \" \" + k\n",
    "            res.append(tmp)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        freq = {}\n",
    "        for cpdomain in cpdomains:\n",
    "           cnt, domian =  cpdomain.split()\n",
    "           cnt = int(cnt)\n",
    "           domian_list = domian.split(\".\")\n",
    "           for index,_ in enumerate(domian_list):\n",
    "               domian = \".\".join(domian_list[index:])\n",
    "               freq[domian] = freq.get(domian,0)+cnt\n",
    "\n",
    "        res = []\n",
    "        for domian,cnt in freq.items():\n",
    "            res.append(f\"{cnt} {domian}\")\n",
    "\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "\n",
    "        # hash table\n",
    "        # for each item:\n",
    "        #  1. split by ' ' to get count and domains\n",
    "        #  2. for rest domains:\n",
    "        #      count domain from left, remove leftmost item separated by . after rach count \n",
    "        \n",
    "        # construct ans list by join count and key by space, then by ,\n",
    "\n",
    "        \n",
    "        count = dict()\n",
    "\n",
    "        for item in cpdomains:\n",
    "            cnt = int(item.split(' ')[0])\n",
    "            domain = item.split(' ')[1]\n",
    "            dom_len = len(domain.split('.'))\n",
    "            while dom_len >= 1:\n",
    "                if domain not in count:\n",
    "                    count[domain] = cnt\n",
    "                else:\n",
    "                    count[domain] += cnt\n",
    "                domain = \".\".join(domain.split('.')[1:])\n",
    "                dom_len -= 1\n",
    "\n",
    "        final = []\n",
    "        for key in count:\n",
    "            ans = str(count[key]) + ' ' + key\n",
    "            final.append(ans)\n",
    "        return final\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        x={}\n",
    "        for i in cpdomains:\n",
    "            nums, weburl = i.split(' ')\n",
    "            nums = int(nums)\n",
    "            partweb = weburl.split('.')\n",
    "            allweb = []            \n",
    "            allweb.append(partweb[-1])\n",
    "            allweb.append('.'.join(partweb[-2:]))\n",
    "            if len(partweb) == 3:\n",
    "                allweb.append('.'.join(partweb))\n",
    "            for k in allweb:\n",
    "                if k not in x:\n",
    "                    x[k] = nums\n",
    "                else:\n",
    "                    x[k] = x[k] + nums\n",
    "        ans = []\n",
    "        for key, value in x.items():\n",
    "            tmpstr = ' '.join([str(value),key])\n",
    "            ans.append(tmpstr)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        ans=dict()\n",
    "        for cp in cpdomains:\n",
    "            num,site=cp.split(\" \")\n",
    "            num=int(num)\n",
    "            site=site.split(\".\")\n",
    "\n",
    "            if len(site)==2:\n",
    "                site_name=\".\".join(site)\n",
    "                if site_name not in ans:\n",
    "                    ans[site_name]=num\n",
    "                else:\n",
    "                    ans[site_name]+=num\n",
    "            else:\n",
    "                site_name=\".\".join(site)\n",
    "                if site_name not in ans:\n",
    "                    ans[site_name]=num\n",
    "                else:\n",
    "                    ans[site_name]+=num\n",
    "\n",
    "                pa=\".\".join(site[-2:])\n",
    "                if pa not in ans:\n",
    "                    ans[pa]=num\n",
    "                else:\n",
    "                    ans[pa]+=num\n",
    "\n",
    "            if site[-1] not in ans:\n",
    "                ans[site[-1]]=num\n",
    "            else:\n",
    "                ans[site[-1]]+=num\n",
    "        \n",
    "        res=[]\n",
    "        for k,v in ans.items():\n",
    "            res.append(str(v)+\" \"+k)\n",
    "        return res\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        字典 = dict()\n",
    "        for i in cpdomains:\n",
    "            访问数, 域名字符串 = i.split()\n",
    "            访问数 = int(访问数)\n",
    "            字典[域名字符串] = 字典.get(域名字符串, 0) + 访问数\n",
    "            while \".\" in 域名字符串:\n",
    "                域名字符串 = 域名字符串[域名字符串.find(\".\")+1:]\n",
    "                字典[域名字符串] = 字典.get(域名字符串, 0) + 访问数\n",
    "        return [str(字典[i]) + \" \"+ i for i in 字典]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        ans={}\n",
    "        for item in cpdomains:\n",
    "            num,name = item.split()\n",
    "            num=int(num)\n",
    "            name_list = name.split('.')\n",
    "            for i in range(len(name_list)):\n",
    "                sub_name='.'.join(name_list[i:])\n",
    "                if sub_name in ans:\n",
    "                    ans[sub_name]+=num\n",
    "                else:\n",
    "                    ans[sub_name]=num\n",
    "        return  [str(v)+' '+k for k,v in ans.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt=Counter()\n",
    "        for dom in cpdomains:\n",
    "            c,s =dom.split()\n",
    "            c=int(c)\n",
    "            cnt[s]+=c\n",
    "            while '.' in s:\n",
    "                s=s[s.index('.')+1:]\n",
    "                cnt[s]+=c\n",
    "        return ['{} {}'.format(c,s) for  s,c in cnt.items()]        \n",
    "\n",
    " \n",
    "        # cnt = Counter()\n",
    "        # for domain in cpdomains:\n",
    "        #     c, s = domain.split()\n",
    "        #     c = int(c)\n",
    "        #     cnt[s] += c\n",
    "        #     while '.' in s:\n",
    "        #         s = s[s.index('.') + 1:]\n",
    "        #         cnt[s] += c\n",
    "        # # return [f'{c} {s}' for s, c in cnt.items()]\n",
    "        # return [\"{} {}\".format(c, s) for s, c in cnt.items()]              "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        mp = {}\n",
    "        for cpdomain in cpdomains:\n",
    "            count_domain = cpdomain.split(' ')\n",
    "            count = int(count_domain[0])\n",
    "            domain = count_domain[1]\n",
    "            mp[domain] = mp.get(domain, 0) + count\n",
    "            i = 0\n",
    "            while i < len(domain):\n",
    "                if domain[i] == '.':\n",
    "                    domain = domain[i + 1:]\n",
    "                    mp[domain] = mp.get(domain, 0) + count\n",
    "                    i = 0\n",
    "                else:\n",
    "                    i += 1\n",
    "        result = []\n",
    "        for key in mp.keys():\n",
    "            result.append(str(mp[key]) + \" \" + str(key))\n",
    "\n",
    "        return result\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt=Counter()\n",
    "        for dom in cpdomains:\n",
    "            c,s=dom.split()\n",
    "            c=int(c)\n",
    "            cnt[s]+=c\n",
    "            while '.' in s:\n",
    "                s=s[s.index('.')+1:]\n",
    "                cnt[s]+=c\n",
    "        return [\"{} {}\".format(c,s) for s,c in cnt.items()]        \n",
    " \n",
    "        # cnt = Counter()\n",
    "        # for domain in cpdomains:\n",
    "        #     c, s = domain.split()\n",
    "        #     c = int(c)\n",
    "        #     cnt[s] += c\n",
    "        #     while '.' in s:\n",
    "        #         s = s[s.index('.') + 1:]\n",
    "        #         cnt[s] += c\n",
    "        # # return [f'{c} {s}' for s, c in cnt.items()]\n",
    "        # return [\"{} {}\".format(c, s) for s, c in cnt.items()]              "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        mapping = {}\n",
    "        for cpdomain in cpdomains:\n",
    "            count, name = cpdomain.split()\n",
    "            domain = \"\"\n",
    "            parts = name.split('.')\n",
    "            for i in range(len(parts) - 1, -1, -1):\n",
    "                domain = parts[i] + '.' + domain if domain else parts[i]\n",
    "                mapping[domain] = mapping.get(domain, 0) + int(count)\n",
    "        \n",
    "        result = []\n",
    "        for key, value in mapping.items():\n",
    "            result.append(str(value) + ' ' + key)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt = defaultdict(int)\n",
    "        for s in cpdomains:\n",
    "            tmp = s.split()\n",
    "            times, name = int(tmp[0]), tmp[1]\n",
    "            cnt[name] += times \n",
    "            for i in range(len(name)):\n",
    "                if name[i] == '.':\n",
    "                    cnt[name[i + 1:]] += times\n",
    "        ans = []\n",
    "        for name, times in cnt.items():\n",
    "            ans.append(str(times) + ' ' + name)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        # 哈希表\n",
    "        cnt_dict = dict()\n",
    "        for cpdomain in cpdomains:\n",
    "            cpdomain = cpdomain.split(' ')\n",
    "            cnt = int(cpdomain[0])\n",
    "            domain = cpdomain[1]\n",
    "            domain = domain.split('.')\n",
    "            tmp = ''\n",
    "            for d in domain[::-1]:\n",
    "                if not tmp:\n",
    "                    tmp = d\n",
    "                else:\n",
    "                    tmp = d + '.' + tmp\n",
    "                cnt_dict[tmp] = cnt_dict.get(tmp, 0) + cnt\n",
    "\n",
    "        ans = []\n",
    "        for domain, cnt in cnt_dict.items():\n",
    "            sub = [str(cnt), domain]\n",
    "            ans.append(' '.join(sub))\n",
    "        \n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        dict_vis={}\n",
    "        for s in cpdomains:\n",
    "            s=s.split(\" \")\n",
    "            n_sum=int(s[0])\n",
    "            n=len(s[1])\n",
    "            for i in range(n):\n",
    "                if i==0 or s[1][i-1]=='.':\n",
    "                    if s[1][i:n] in dict_vis : dict_vis[s[1][i:n]]+=n_sum\n",
    "                    else : dict_vis.update({s[1][i:n]:n_sum})\n",
    "        List_vv=[]\n",
    "        for ss in dict_vis:\n",
    "            List_vv.append(str(dict_vis[ss])+' '+ss)\n",
    "        return List_vv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from typing import List\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt = Counter()\n",
    "        for domain in cpdomains:\n",
    "            c, s = domain.split()\n",
    "            c = int(c)\n",
    "            cnt[s] += c\n",
    "            while \".\" in s:\n",
    "                s = s[s.index(\".\") + 1 :]\n",
    "                cnt[s] += c\n",
    "        return [f\"{c} {s}\" for s, c in cnt.items()]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        m = defaultdict(int)\n",
    "        res = []\n",
    "        for item in cpdomains:\n",
    "            itemDetail = item.split(\" \")\n",
    "            num = int(itemDetail[0])\n",
    "            domains = itemDetail[1]\n",
    "\n",
    "            for i in range(len(domains)-1, -1, -1):\n",
    "                if domains[i] == \".\":\n",
    "                    curDomain = domains[i+1:]\n",
    "                    m[curDomain] += num\n",
    "            m[domains] += num\n",
    "        print(m)\n",
    "        for k, v in m.items():\n",
    "            curItem = \"\"\n",
    "            curItem += str(v)\n",
    "            curItem += \" \"\n",
    "            curItem += str(k)\n",
    "            res.append(curItem)\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\r\n",
    "        res=defaultdict(int)\r\n",
    "        for cpd in cpdomains:\r\n",
    "            cpd=cpd.split()\r\n",
    "            count=int(cpd[0])\r\n",
    "            domain=cpd[1].split('.')\r\n",
    "            for i in range(len(domain)):\r\n",
    "                res['.'.join(domain[i:])]+=count\r\n",
    "        ans=[]\r\n",
    "        for k,v in res.items():\r\n",
    "            ans.append(f'{v} {k}')\r\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt=Counter()\n",
    "        for dom in cpdomains:\n",
    "            c,s=dom.split()\n",
    "            c=int(c)\n",
    "            cnt[s]+=c\n",
    "            while '.' in s:\n",
    "                s=s[s.index('.')+1:]\n",
    "                cnt[s]+=c\n",
    "        return ['{} {}'.format(c,s) for s,c in cnt.items()]        \n",
    "\n",
    "      \n",
    " \n",
    "        # cnt = Counter()\n",
    "        # for domain in cpdomains:\n",
    "        #     c, s = domain.split()\n",
    "        #     c = int(c)\n",
    "        #     cnt[s] += c\n",
    "        #     while '.' in s:\n",
    "        #         s = s[s.index('.') + 1:]\n",
    "        #         cnt[s] += c\n",
    "        # # return [f'{c} {s}' for s, c in cnt.items()]\n",
    "        # return [\"{} {}\".format(c, s) for s, c in cnt.items()]              "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        map = {}\n",
    "\n",
    "        for s in cpdomains:\n",
    "            n = len(s)\n",
    "            idx = 0 \n",
    "            while idx<n and s[idx] != ' ':\n",
    "                idx +=1\n",
    "            cnt = int(s[:idx])\n",
    "            start = idx +1\n",
    "            idx = n-1\n",
    "\n",
    "            while idx >= start:\n",
    "                while idx >= start and s[idx] != '.':\n",
    "                    idx -=1\n",
    "\n",
    "                cur = s[idx+1:]\n",
    "                map[cur] = map.get(cur,0) + cnt\n",
    "                idx -=1\n",
    "\n",
    "        ans = []\n",
    "        for key in map:\n",
    "            ans.append(str(map[key]) + ' '+key)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    # def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "    #     from collections import defaultdict\n",
    "    #     domain_map = defaultdict(int)\n",
    "    #     for cpdomain in cpdomains:\n",
    "    #         rep, domain = cpdomain.split(' ')\n",
    "    #         sub_domins = domain.split('.')\n",
    "    #         for i in range(len(sub_domins)):\n",
    "    #             domain_map['.'.join(sub_domins[i:])] += int(rep)\n",
    "    #     return ['{} {}'.format(v, k) for k, v in domain_map.items()]\n",
    "\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        from collections import defaultdict\n",
    "        domain_map = defaultdict(int)\n",
    "        for cpdomain in cpdomains:\n",
    "            left, right = 0, len(cpdomain) - 1\n",
    "            while left <= right and cpdomain[left] != ' ':  # 从左到右找' '\n",
    "                left += 1\n",
    "            rep = cpdomain[:left]\n",
    "            left, right = left + 1, right\n",
    "            while left <= right:   # 从右到左找'.'\n",
    "                while left <= right and cpdomain[right] != '.':\n",
    "                    right -= 1\n",
    "                domain_map[cpdomain[right+1:]] += int(rep)\n",
    "                right -= 1\n",
    "        return ['{} {}'.format(v, k) for k, v in domain_map.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        temp = {}\n",
    "        for i in range(len(cpdomains)):\n",
    "            string = cpdomains[i]\n",
    "            num = string.split()[0]\n",
    "            domain = string.split()[1].split('.')\n",
    "            if len(domain) == 2:\n",
    "                sub_1 = domain[-1]\n",
    "                sub_2 = domain[-2] + '.' + domain[-1]\n",
    "                if sub_1 not in temp:\n",
    "                    temp[sub_1] = int(num)\n",
    "                else:\n",
    "                    temp[sub_1] += int(num)\n",
    "                if sub_2 not in temp:\n",
    "                    temp[sub_2] = int(num)\n",
    "                else:\n",
    "                    temp[sub_2] += int(num)\n",
    "            elif len(domain) == 3:\n",
    "                sub_1 = domain[-1]\n",
    "                sub_2 = domain[-2] + '.' + domain[-1]\n",
    "                sub_3 = string.split()[1]\n",
    "                if sub_1 not in temp:\n",
    "                    temp[sub_1] = int(num)\n",
    "                else:\n",
    "                    temp[sub_1] += int(num)\n",
    "                if sub_2 not in temp:\n",
    "                    temp[sub_2] = int(num)\n",
    "                else:\n",
    "                    temp[sub_2] += int(num)\n",
    "                if sub_3 not in temp:\n",
    "                    temp[sub_3] = int(num)\n",
    "                else:\n",
    "                    temp[sub_3] += int(num)\n",
    "        res = []\n",
    "        for k, v in temp.items():\n",
    "            data = str(v) + ' ' + k\n",
    "            res.append(data)\n",
    "        return res\n",
    "                \n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        \n",
    "        \n",
    "        \n",
    "        # my solution ... \n",
    "        \n",
    "        f = {}\n",
    "        for s in cpdomains:\n",
    "            c, d = s.split()\n",
    "            c = int(c)\n",
    "            f[d] = f.get(d, 0) + c\n",
    "            i = 0\n",
    "            while True:\n",
    "                i = d.find('.', i) + 1\n",
    "                if not i:\n",
    "                    break\n",
    "                f[d[i:]] = f.get(d[i:], 0) + c\n",
    "        return [str(f[s]) + ' ' + s for s in f]\n",
    "        \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        d={}\n",
    "        for i in cpdomains:\n",
    "            x,y=i.split()\n",
    "            x=int(x)\n",
    "            if y in d:\n",
    "                d[y]+=x\n",
    "            else:\n",
    "                d[y]=x\n",
    "            n=len(y)\n",
    "            for i in range(n):\n",
    "                if y[i]=='.':\n",
    "                    s=y[i+1::]\n",
    "                    if s in d:\n",
    "                        d[s]+=x\n",
    "                    else:\n",
    "                        d[s]=x\n",
    "        ans=[]\n",
    "        for i in d:\n",
    "            ans.append(str(d[i])+' '+str(i))\n",
    "        return ans\n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        dic=defaultdict(int)\n",
    "        for domain in cpdomains:\n",
    "            num,internet=domain.split()\n",
    "            num=int(num)\n",
    "            dic[internet]+=num\n",
    "            for i in internet:\n",
    "                if(i=='.'):\n",
    "                    internet=internet[internet.index('.')+1:]\n",
    "                    dic[internet]+=num\n",
    "        return [f\"{num} {st}\"for st,num in dic.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from typing import List\n",
    "class MyTree:\n",
    "    def __init__(self) -> None:\n",
    "        self.data = ['ROOT', 0, []]\n",
    "    \n",
    "    def update(self, path: list[str], freq: int):\n",
    "        path.append('ROOT')\n",
    "        length = len(path) - 1\n",
    "\n",
    "        def dfs(node: list, length: int):\n",
    "            \n",
    "            node[1] += freq\n",
    "            nexts = node[2]\n",
    "            length -= 1\n",
    "            \n",
    "            if length < 0:\n",
    "                return\n",
    "\n",
    "            have_flg = False\n",
    "            for index in range(len(nexts)):\n",
    "                if nexts[index][0] == path[length]:\n",
    "                    dfs(nexts[index], length)\n",
    "                    have_flg = True\n",
    "\n",
    "            if not have_flg:\n",
    "                nexts.append([path[length], 0, []])\n",
    "                dfs(nexts[-1], length)\n",
    "        \n",
    "        dfs(self.data, length)\n",
    "\n",
    "    def print(self):\n",
    "\n",
    "        result = []\n",
    "\n",
    "        def dfs(node: list, domain: list) -> None:\n",
    "            domain.append(node[0])\n",
    "            result.append(str(node[1]) + ' ' + '.'.join(domain[::-1]))\n",
    "\n",
    "            if not node[2]:\n",
    "                return\n",
    "            else:\n",
    "                for sub_node in node[2]:\n",
    "                    dfs(sub_node, domain.copy())\n",
    "        \n",
    "        for sub in self.data[2]:\n",
    "            dfs(sub, [])\n",
    "\n",
    "        return result\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        \n",
    "        tree = MyTree()\n",
    "\n",
    "        for cp_domain in cpdomains:\n",
    "            freq, domain = cp_domain.split()\n",
    "            freq = int(freq)\n",
    "            domains = domain.split('.')\n",
    "\n",
    "            tree.update(domains, freq)\n",
    "        \n",
    "        return tree.print()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        if True:\n",
    "            from collections import defaultdict\n",
    "            results = defaultdict(int)\n",
    "            for cpdomain in cpdomains:\n",
    "                cp, domain = cpdomain.split()\n",
    "                results[domain] +=int(cp)\n",
    "                while \".\" in domain:\n",
    "                    domain = domain[domain.index(\".\")+1:]\n",
    "                    results[domain] +=int(cp)\n",
    "            results = [\"%s %s\"%(v, k) for k,v in results.items()]\n",
    "            return results\n",
    " \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "        elif False:\n",
    "            from collections import defaultdict\n",
    "            #condition\n",
    "            \n",
    "            results = defaultdict(int)\n",
    "            def get_domains(domain):\n",
    "                domains = []\n",
    "                sub_domains = domain.split(\".\")[::-1]\n",
    "                for i in range(len(sub_domains)):\n",
    "                    domains.append(\".\".join(sub_domains[:i+1][::-1]))\n",
    "                return domains\n",
    "\n",
    "            for cpdomain in cpdomains:\n",
    "                cp, domain = cpdomain.split()\n",
    "                domains = get_domains(domain)\n",
    "                for domain in domains:\n",
    "                    results[domain] += int(cp)\n",
    "            \n",
    "            return [\"%s %s\"%(v, k) for k,v in results.items()]\n",
    "                \n",
    "                \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        c = Counter()\n",
    "        for a,b in map(lambda s: s.split(' '), cpdomains):\n",
    "            a = int(a)\n",
    "            c[b] += a\n",
    "            for i in range(len(b)):\n",
    "                if b[i] == '.':\n",
    "                    c[b[i+1:]] += a\n",
    "        \n",
    "        res = []\n",
    "        for i,v in c.items():\n",
    "            res.append(str(v) + ' ' + i)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        counter = dict()\n",
    "        for item in cpdomains:\n",
    "            i = 0\n",
    "            while item[i] != ' ': i += 1\n",
    "\n",
    "            v_cnt = int(item[0: i])\n",
    "            domain = item[i + 1: ]\n",
    "            for i in range(len(domain) - 1, -1, -1):\n",
    "                if domain[i] == '.' or i == 0:\n",
    "                    start = i + 1\n",
    "                    if i == 0: start = i \n",
    "                    d = ''.join(domain[start: ])\n",
    "                    counter[d] = counter.get(d, 0) + v_cnt\n",
    "\n",
    "        ans = []\n",
    "        for k, v in counter.items():\n",
    "            ans.append('{} {}'.format(v, k)) \n",
    "\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\r\n",
    "        cnt={}\r\n",
    "        for cp in cpdomains:\r\n",
    "            v,domain=cp.split(' ')\r\n",
    "            v=int(v)\r\n",
    "            # for i in range(len(domain)-1,-1,-1):\r\n",
    "            parts=domain.split('.')\r\n",
    "            for i in range(len(parts)):\r\n",
    "                key='.'.join(parts[i:])\r\n",
    "                cnt[key]=cnt.get(key,0)+v\r\n",
    "        return [f'{v} {k}' for k,v in cnt.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        from collections import defaultdict\n",
    "        domain_map = defaultdict(int)\n",
    "        for cpdomain in cpdomains:\n",
    "            rep, domain = cpdomain.split(' ')\n",
    "            sub_domins = domain.split('.')\n",
    "            for i in range(len(sub_domins)):\n",
    "                domain_map['.'.join(sub_domins[i:])] += int(rep)\n",
    "        return ['{} {}'.format(v, k) for k, v in domain_map.items()]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        def chaifen(str1):\n",
    "            list1 = str1.split()\n",
    "            str2 = list1[1]\n",
    "            res1 = [-1]\n",
    "            for i in range(len(str2)):\n",
    "                if str2[i] == \".\":\n",
    "                    res1.append(i)\n",
    "            res2 = []\n",
    "            for j in res1:\n",
    "                res2.append([int(list1[0]) , str2[j+1:]])\n",
    "            return res2\n",
    "        res = []\n",
    "        for i in cpdomains:\n",
    "            stack = chaifen(i)\n",
    "            for i in stack:\n",
    "                res.append(i)\n",
    "        res4 = []\n",
    "        for i in res:\n",
    "            res4.append(i[1])\n",
    "        res5 = list(set(res4))\n",
    "        res6 = []\n",
    "        for i in res5:\n",
    "            num = 0\n",
    "            for j in res:\n",
    "                if i == j[1]:\n",
    "                    num += j[0]\n",
    "            res6.append([num,i])\n",
    "        res7 = []\n",
    "        for m in res6:\n",
    "            res7.append(str(m[0]) + \" \" + m[1])\n",
    "        return res7\n",
    "\n",
    "\n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        mp: Dict[str,int] = {}\n",
    "        for str_domain in cpdomains:\n",
    "            time = int(str_domain.split(' ')[0])\n",
    "            domain_name = str_domain.split(' ')[1]\n",
    "            if domain_name not in mp:\n",
    "                mp[domain_name] = 0\n",
    "            mp[domain_name] += time\n",
    "        \n",
    "            for i in range(len(domain_name)-1,-1,-1):\n",
    "                if domain_name[i] == '.':\n",
    "                    sub_domain = domain_name[i + 1:]\n",
    "                    if sub_domain not in mp:\n",
    "                        mp[sub_domain] = 0\n",
    "                    mp[sub_domain] += time\n",
    "        ans = []\n",
    "        for k,v in mp.items():\n",
    "            res = f\"{v} {k}\"\n",
    "            ans.append(res)\n",
    "        return ans\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        return_dict_with_frequency = {}\n",
    "        for single_URL in cpdomains:\n",
    "            temp_dict_with_frequency = {}\n",
    "            temp_number = \"\".join(\n",
    "                map(str, re.compile(\"[0-9]\").findall(single_URL)))\n",
    "            # temp_number = str(re.findall(r\"[0-9]+\", single_URL[0]))\n",
    "            URL_elements = list(single_URL.replace(\n",
    "                temp_number, \"\").lstrip().split(\".\"))\n",
    "            temp_number = int(temp_number)\n",
    "            if len(URL_elements) == 2:\n",
    "                temp_dict_with_frequency.update(\n",
    "                    {URL_elements[1]: temp_number, URL_elements[0]+\".\"+URL_elements[1]: temp_number})\n",
    "            else:\n",
    "                temp_dict_with_frequency.update(\n",
    "                    {URL_elements[2]: temp_number, URL_elements[1]+\".\"+URL_elements[2]: temp_number, URL_elements[0]+\".\"+URL_elements[1]+\".\"+URL_elements[2]: temp_number})\n",
    "            for single_element in temp_dict_with_frequency:\n",
    "                if return_dict_with_frequency.get(single_element, False) :\n",
    "                    return_dict_with_frequency[single_element] += temp_dict_with_frequency[single_element]\n",
    "                else:\n",
    "                    return_dict_with_frequency.update(\n",
    "                        {single_element: temp_dict_with_frequency[single_element]})\n",
    "        return [str(list(return_dict_with_frequency.values())[index])+\" \"+list(return_dict_with_frequency.keys())[index] for index in range(len(return_dict_with_frequency))]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        dom_dict = {}\n",
    "        for s in cpdomains:\n",
    "            slist = s.split(' ')\n",
    "            num = int(slist[0])\n",
    "            domain = slist[1]\n",
    "            dom_dict[domain] = num + dom_dict.get(domain, 0)\n",
    "            for i in range(len(domain)):\n",
    "                if domain[i] == '.':\n",
    "                    dom_dict[domain[i + 1 :]] = num + dom_dict.get(domain[i + 1 :], 0)\n",
    "        ans = []\n",
    "        for k, v in dom_dict.items():\n",
    "            ans.append(str(v) + ' ' + k)\n",
    "        return ans\n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        cnt = defaultdict(int)\n",
    "        for s in cpdomains:\n",
    "            tmp = s.split()\n",
    "            times, name = int(tmp[0]), tmp[1]\n",
    "            cnt[name] += times \n",
    "            for i in range(len(name)):\n",
    "                if name[i] == '.':\n",
    "                    cnt[name[i + 1:]] += times\n",
    "        ans = []\n",
    "        for name, times in cnt.items():\n",
    "            ans.append(f'{times} {name}')\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        m = {}\n",
    "        for domain in cpdomains:\n",
    "            row = domain.split(\" \")\n",
    "            cnt, items = int(row[0]), row[1].split(\".\")\n",
    "            one = items[-1]\n",
    "            tow = \".\".join(items[-2:])\n",
    "            three = row[1]\n",
    "            if one not in m.keys():\n",
    "                m[one] = cnt\n",
    "            else:\n",
    "                m[one] += cnt\n",
    "            if tow not in m.keys():\n",
    "                m[tow] = cnt\n",
    "            else:\n",
    "                m[tow] += cnt\n",
    "            if len(items) == 3:\n",
    "                if three not in m.keys():\n",
    "                    m[three] = cnt\n",
    "                else:\n",
    "                    m[three] += cnt\n",
    "        ans = []\n",
    "        for key, cnt in m.items():\n",
    "            ans.append(\"{} {}\".format(cnt, key))\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        m = {}\n",
    "        for s in cpdomains:\n",
    "            count, addr = s.split(\" \")\n",
    "            count = int(count)\n",
    "            addr_list = addr.split(\".\")\n",
    "            if addr not in m:\n",
    "                m[addr] = 0\n",
    "            m[addr] += count\n",
    "            if len(addr_list) == 3:\n",
    "                add_l1 = \".\".join(addr_list[1:])\n",
    "                add_l2 = addr_list[-1]\n",
    "                if add_l1 not in m:\n",
    "                    m[add_l1] = 0\n",
    "                m[add_l1] += count\n",
    "                if add_l2 not in m:\n",
    "                    m[add_l2] = 0\n",
    "                m[add_l2] += count\n",
    "            elif len(addr_list) == 2:\n",
    "                add_l1 = addr_list[-1]\n",
    "                if add_l1 not in m:\n",
    "                    m[add_l1] = 0\n",
    "                m[add_l1] += count\n",
    "        ans = []\n",
    "        for k,v in m.items():\n",
    "            ans.append(str(v)+\" \" + k)\n",
    "        return ans\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "\n",
    "        d = {}\n",
    "\n",
    "        \n",
    "        for s in cpdomains:\n",
    "            \n",
    "            idx = 0\n",
    "            l = len(s)    \n",
    "            while idx<l and  s[idx] != \" \":\n",
    "                idx += 1\n",
    "            \n",
    "            cnt = int(s[:idx])\n",
    "\n",
    "            start = idx + 1\n",
    "            end = l - 1\n",
    "            while start <= end:\n",
    "\n",
    "                while start  <= end and s[end] != \".\":\n",
    "                    end -= 1\n",
    "                \n",
    "                cur = s[end+1:]\n",
    "\n",
    "                d[cur] = d.get(cur, 0 ) + cnt \n",
    "\n",
    "                end -= 1\n",
    "\n",
    "            \n",
    "        ans = []\n",
    "        for key in d:\n",
    "            ans.append(str(d[key]) + \" \" + key)\n",
    "\n",
    "        return ans \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n",
    "        hash = {}\n",
    "        for item in cpdomains:\n",
    "            time = int(item.split(' ')[0])\n",
    "            domains = []\n",
    "            for index,c in enumerate(item):\n",
    "                if c in ' .':\n",
    "                    hash[item[index+1:]] = hash[item[index+1:]] + time if item[index+1:] in hash else time\n",
    "        return [f'{time} {domain}' for domain,time in hash.items()]\n",
    "            \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\r\n",
    "        cnt={}\r\n",
    "        for cp in cpdomains:\r\n",
    "            v,domain=cp.split(' ')\r\n",
    "            v=int(v)\r\n",
    "            # for i in range(len(domain)-1,-1,-1):\r\n",
    "            cnt[domain]=cnt.get(domain,0)+v\r\n",
    "            parts=domain.split('.')\r\n",
    "            for i in range(1,len(parts)):\r\n",
    "                key='.'.join(parts[i:])\r\n",
    "                cnt[key]=cnt.get(key,0)+v\r\n",
    "        return [f'{v} {k}' for k,v in cnt.items()]"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
